package com.linkwechat.framework.interceptor;

import com.linkwechat.common.config.TetantConfig;
import com.linkwechat.common.core.domain.entity.SysUser;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.enums.TetantInfoTransferMode;
import com.linkwechat.common.enums.TetantType;
import com.linkwechat.common.utils.ServletUtils;
import com.linkwechat.common.tenant.TenantContextHolder;
import com.linkwechat.system.domain.SysTenant;
import com.linkwechat.system.service.ISysTenantService;
import com.linkwechat.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

@Component
public class ResovleTenantInfoInterceptorAdapter extends HandlerInterceptorAdapter {

    @Resource
    TetantConfig tetantConfig;
    @Resource
    RedisCache redisCache;
    @Resource
    ISysTenantService tenantService;
    @Resource
    ISysUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
//            String fullurl=ServletUtils.getRequest().getRequestURL().toString();
            String url=ServletUtils.getRequest().getRequestURI();
            if(url.equals("/login")){
                if(tetantConfig.getType().equals(TetantType.NONE.getType())){
                    TenantContextHolder.setTenantCode("0");
                    return true;
                }

                if(tetantConfig.getType().equals(TetantType.COLUMN.getType())){

                    // 前端vue代理转发过来的没有原来的数据，无法获取到本来服务端uri
                    String originName= ServletUtils.getRequest().getHeader("referer");

                    String tenantCode=null;
                    if(tetantConfig.getTetantInfoTransferMode().equals(TetantInfoTransferMode.TRANSFER_DOMAIN.getMode())){
                        tenantCode=redisCache.getCacheObject(originName);
                        if(tenantCode==null){
                            SysTenant sysTenant =tenantService.queryDomainMapperTenant(originName);
                            redisCache.setCacheObject(originName,sysTenant.getTenantCode());
                            tenantCode=sysTenant.getTenantCode();
                        }

                    }else if(tetantConfig.getTetantInfoTransferMode().equals(TetantInfoTransferMode.TRANSFER_QUERY_PARAM.getMode())){
                        tenantCode=ServletUtils.getRequest().getParameter("tenantCode");
                    }else if(tetantConfig.getTetantInfoTransferMode().equals(TetantInfoTransferMode.TRANSFER_MIXED.getMode())){
                        tenantCode=ServletUtils.getRequest().getParameter("tenantCode");
                        // 还为空就走域名
                        if(StringUtils.isEmpty(tenantCode)){
                            tenantCode=redisCache.getCacheObject(originName);
                            if(tenantCode==null){
                                // 如是平台域名直接走
                                if(!tetantConfig.getPlatformBindDomains().isEmpty()&&tetantConfig.getPlatformBindDomains().contains(originName)){
                                    TenantContextHolder.setTenantCode("0");
                                    return true;
                                }
                                // 否则走定义租户域名
                                SysTenant sysTenant =tenantService.queryDomainMapperTenant(originName);
                                redisCache.setCacheObject(originName,sysTenant.getTenantCode());
                                tenantCode=sysTenant.getTenantCode();
                            }
                        }

                        if(StringUtils.isEmpty(tenantCode)){
                            List<SysUser> sysUsers=userService.selectUserList(SysUser.builder().userName(request.getParameter("username")).build());
                            TenantContextHolder.setSysUsers(sysUsers);
                        }

                    }


                    TenantContextHolder.setTenantCode(tenantCode);
                }
                if(tetantConfig.getType().equals(TetantType.SCHEMA.getType()) || tetantConfig.getType().equals(TetantType.DATABASE.getType())){
                    // 这里需要调用引用的数据源

                }
            }
            return true;

        }else{
            return super.preHandle(request, response, handler);
        }


    }
}
